package com.ruoyi.feike.controller;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.ExcelExportUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.ExcelExp;
import com.ruoyi.feike.domain.InsuranceAddress;
import com.ruoyi.feike.domain.InvoiceInformation;
import com.ruoyi.feike.domain.NewSumKeep;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.mapper.ReportInsuranceThreeMapper;
import com.ruoyi.system.service.ISysPostService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.feike.domain.ReportInsuranceThree;
import com.ruoyi.feike.service.IReportInsuranceThreeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 报表h_report-insurance-3Controller
 * 
 * @author ruoyi
 * @date 2022-12-27
 */
@RestController
@RequestMapping("/feike/reportInsuranceThree")
public class ReportInsuranceThreeController extends BaseController
{
    @Autowired
    private IReportInsuranceThreeService reportInsuranceThreeService;
    @Autowired
    private ReportInsuranceThreeMapper reportInsuranceThreeMapper;

    @Autowired
    private ISysPostService postService;

    /**
     * 查询报表h_report-insurance-3列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ReportInsuranceThree reportInsuranceThree)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        boolean flag = false;
        List<String> strings = postService.selectPostListByUserId1(loginUser.getUser().getUserId());
        for (String post : strings) {
            if(post.contains("op")){
                flag = true;
                break;
            }
        }
        startPage();
        List<ReportInsuranceThree> list = reportInsuranceThreeService.selectReportInsuranceThreeList(reportInsuranceThree);
        for (ReportInsuranceThree reportInsurance : list) {
            reportInsurance.setOpFlag("2");
            if(flag){
                reportInsurance.setOpFlag("1");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出报表h_report-insurance-3列表
     */
    @Log(title = "报表h_report-insurance-3", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ReportInsuranceThree reportInsuranceThree)
    {
        List<ReportInsuranceThree> list = reportInsuranceThreeService.selectReportInsuranceThreeList(reportInsuranceThree);
        ExcelUtil<ReportInsuranceThree> util = new ExcelUtil<ReportInsuranceThree>(ReportInsuranceThree.class);
        return util.exportExcel(list, "reportInsuranceThree");
    }

    /**
     * 获取报表h_report-insurance-3详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(reportInsuranceThreeService.selectReportInsuranceThreeById(id));
    }

    /**
     * 新增报表h_report-insurance-3
     */
    @Log(title = "报表h_report-insurance-3", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ReportInsuranceThree reportInsuranceThree)
    {
        return toAjax(reportInsuranceThreeService.insertReportInsuranceThree(reportInsuranceThree));
    }

    /**
     * 修改报表h_report-insurance-3
     */
    @Log(title = "报表h_report-insurance-3", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ReportInsuranceThree reportInsuranceThree)
    {
        return toAjax(reportInsuranceThreeService.updateReportInsuranceThree(reportInsuranceThree));
    }

    /**
     * 删除报表h_report-insurance-3
     */
    @Log(title = "报表h_report-insurance-3", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(reportInsuranceThreeService.deleteReportInsuranceThreeByIds(ids));
    }

    private static class ExcelExp {
        private String fileName;// sheet的名称
        private String[] handers;// sheet里的标题
        private List<String[]> dataset;// sheet里的数据集
        private String tableName;

        public ExcelExp(String fileName, String[] handers, List<String[]> dataset, String tableName) {
            this.fileName = fileName;
            this.handers = handers;
            this.dataset = dataset;
            this.tableName = tableName;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String[] getHanders() {
            return handers;
        }

        public void setHanders(String[] handers) {
            this.handers = handers;
        }

        public List<String[]> getDataset() {
            return dataset;
        }

        public void setDataset(List<String[]> dataset) {
            this.dataset = dataset;
        }

        public String getTableName() {
            return tableName;
        }

        public void setTableName(String tableName) {
            this.tableName = tableName;
        }
    }

    @GetMapping("/common/download/report/{startDate}/{endDate}")
    public void fileDownloadReport(@PathVariable String startDate,@PathVariable String endDate,HttpServletResponse response, HttpServletRequest request){
//        String startDate = map.get("startDate").toString();
//        String endDate = map.get("endDate").toString();
        List<Map<String, Object>> instanceIdList2 = reportInsuranceThreeMapper.getInstanceIdList2(startDate, endDate);
        List<Map<String, Object>> instanceIdList3 = reportInsuranceThreeMapper.getInstanceIdList3(startDate, endDate);
        Double sum = 0.00;
        for(Map<String, Object> inthree : instanceIdList3){
            Double premium = Convert.toDouble(inthree.get("premium"));
            sum = premium+sum;
        }
        BigDecimal bg = new BigDecimal(sum);
        BigDecimal bigDecimal = bg.setScale(2, BigDecimal.ROUND_HALF_UP);
        int i =0;
        List<String[]>stringsList = new ArrayList<>();
        for (Map<String, Object> map : instanceIdList2) {
            i++;
            String[] strings = new String[9];
            strings[0] = map.get("instanceId") == null ? "" : map.get("instanceId").toString();
            strings[1] = Convert.toStr(i);
            strings[2] = map.get("dealerName") == null ? "" : map.get("dealerName").toString();
            strings[3] = map.get("sector") == null ? "" : map.get("sector").toString();
            strings[4] = map.get("premium") == null ? "" : map.get("premium").toString();
            strings[5] = map.get("bankFeedbackNo") == null ? "" : map.get("bankFeedbackNo").toString();
            strings[6] = map.get("premiumReceivedDate") == null ? "" : map.get("premiumReceivedDate").toString();
            strings[7] = map.get("receivedAmount") == null ? "" : map.get("receivedAmount").toString();
            strings[8] = map.get("noteOne") == null ? "" : map.get("noteOne").toString();
            stringsList.add(strings);
        }
        if(stringsList.size()!=0) {
            String[] strings1 = new String[9];
            strings1[0] = "";
            strings1[1] = "";
            strings1[2] = "";
            strings1[3] = "Total";
            strings1[4] = bigDecimal.toString();
            strings1[5] = "";
            strings1[6] = "";
            strings1[7] = "";
            strings1[8] = "";
            stringsList.add(strings1);
            String[] strings2 = new String[9];
            strings2[0] = "";
            strings2[1] = "";
            strings2[2] = "";
            strings2[3] = "";
            strings2[4] = "";
            strings2[5] = "";
            strings2[6] = "";
            strings2[7] = "";
            strings2[8] = "";
            stringsList.add(strings2);
            String[] strings4 = new String[9];
            strings4[0] = "";
            strings4[1] = "Sector";
            strings4[2] = "Premium（Payment amount）";
            strings4[3] = "";
            strings4[4] = "";
            strings4[5] = "";
            strings4[6] = "";
            strings4[7] = "";
            strings4[8] = "";
            stringsList.add(strings4);
            for (Map<String, Object> map : instanceIdList3) {
                String[] strings = new String[9];
                strings[0] = "";
                strings[1] = map.get("sector") == null ? "" : map.get("sector").toString();
                if(map.get("premium") != null){
                    Double premium = (Double)map.get("premium");
                    BigDecimal sum1 = new BigDecimal(premium);
                    BigDecimal bigDecimalSum1 = sum1.setScale(2, BigDecimal.ROUND_HALF_UP);
                    strings[2] =  bigDecimalSum1.toString();
                }else{
                    strings[2] =  "";
                }
                strings[3] = "";
                strings[4] = "";
                strings[5] = "";
                strings[6] = "";
                strings[7] = "";
                strings[8] = "";
                stringsList.add(strings);
            }
            String[] strings3 = new String[9];
            strings3[0] = "";
            strings3[1] = "Total";
            strings3[2] = bigDecimal.toString();
            strings3[3] = "";
            strings3[4] = "";
            strings3[5] = "";
            strings3[6] = "";
            strings3[7] = "";
            strings3[8] = "";
            stringsList.add(strings3);
        }
        ExcelExportUtil.abc(stringsList,null,request,response);
    }
}
